package com.bootcamp.javase2.network.client_server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.TreeMap;

/**
 * @program: day22NetworkCode
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-16 19:55
 **/

public class Server {
    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) throws IOException {
        // server object
        ServerSocket serverSocket = new ServerSocket(9999);
        // accept socket
        Socket socket = serverSocket.accept();
        // get input stream
        InputStream in = socket.getInputStream();
        // choose console or txt
        int choice;
        while ((choice = showMenu()) != 0) {
            if (choice==1) printToConsole(in);
            if (choice==2) exportToTxt(in);
        }
//        printToConsole(in);
//        exportToTxt(in);
        // close
        socket.close();
        serverSocket.close();
    }

    private static void exportToTxt(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        BufferedWriter writer = new BufferedWriter(new FileWriter("server.txt",true));
        String line;
        while ((line=reader.readLine())!=null){
            writer.write(line);
            writer.newLine();
        }
        reader.close();
        writer.close();
    }

    private static void printToConsole(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line=reader.readLine())!=null){
            System.out.println(line);
        }
        reader.close();
    }

    static int showMenu() {
        System.out.println("--- 服务端选择 ---");
        System.out.println(" 1. 输出到console");
        System.out.println(" 2. 储存到server.txt");
        System.out.println(" 0. exit");
        System.out.print("please input:  ");
        int choice = -1;
        while (choice == -1) {
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                choice = -1;
            }
        }
        return choice;
    }
}
